<?php

defined('SYSPATH') or die('No direct script access.');

class Adcategory {

    private static $instances;
    private $data;

    public static function & instances($id = 0) {

        if (!isset(self::$instances[$id])) {
            $class = __CLASS__;
            self::$instances[$id] = new $class($id);
        }
        return self::$instances[$id];
    }

    public function __construct($id) {

        $this->data = NULL;
        $this->_load($id);
    }

    public function _load($id) {

        if (!$id)
            return FALSE;

        $result = ORM::factory('ads_category')
                ->where('id_category', '=', $id)
                ->find()
                ->as_array();

        $this->data = $result ? $result : array();
    }

    public function get($key = NULL) {

        if (is_null($key)) {
            return $this->data;
        } else {
            return isset($this->data[$key]) ? $this->data[$key] : NULL;
        }
    }

    public function set($data) {

        $adcategory = ORM::factory('ads_category');
        $adcategory->values($data);
        if ($adcategory->check()) {
            $adcategory->save();
            if ($adcategory->saved()) {
                return true;
            }
        }

        return false;
    }

    public function update($data) {
        $adcategory = ORM::factory('ads_category')
                ->where('id_category', '=', $this->data['id_category'])
                ->find();

        if (!$adcategory->loaded()) {
            return false;
        } else {
            $adcategory->values($data);
            if ($adcategory->check()) {
                $adcategory->save();
                if ($adcategory->saved()) {
                    return true;
                }
            }
        }
    }

    public function delete() {
        $adcategory = ORM::factory('ads_category', $this->data['id_category']);
        if ($adcategory->loaded()) {
            return $adcategory->delete();
        } else {
            return FALSE;
        }
    }

    public function get_categories($id = '') {
        $ads_category = ORM::factory('ads_category')->find_all()->as_array();
        foreach ($ads_category as $key => $value) {
            $ads_categories[$value->id_category] = $value->name;
        }
        return $ads_categories;
    }

}

